/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { toNumber, toString } from 'lodash';
import { useState } from 'react';

type FormData = {
  curve: pickedLineData;
  plane: pickedFaceData;
  limitPoint: pickedVertexData;
  upPoint: pickedVertexData;
  downPoint: pickedVertexData;
  xc: string;
};

type Params = {
  curve: string;
  plane: string;
  points: string[];
  xc: number[];
};

function CommandReSamplingCurve({
  title,
  onClose,
  props,
}: CurvedCmdDialogParams) {
  const initData: FormData = {
    curve: null,
    plane: null,
    limitPoint: null,
    upPoint: null,
    downPoint: null,
    xc: null,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  const execute = async (preview: boolean) => {
    const { curve, plane, limitPoint, upPoint, downPoint, xc } = formData;

    const points = [limitPoint.vertexId, upPoint.vertexId, downPoint.vertexId];

    const getFinalXc = (xc: string) => {
      const xcArr = xc.split(' ').map((i) => toNumber(i));
      // 升序
      return xcArr.sort((a, b) => a - b);
    };

    const params: Params = {
      curve: curve.edgeId,
      plane: plane.meshId,
      points: points,
      xc: getFinalXc(xc),
    };

    await confirmCommand({ type: 'Resample', a: params }, preview);
  };

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { curve, plane, points, xc } = params;

    await initEditDependency([curve, plane]);

    setFormData({
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
      plane: picker.generatePickObjByPickID(plane) as pickedFaceData,
      limitPoint: picker.generatePickObjByPickID(points[0]) as pickedVertexData,
      upPoint: picker.generatePickObjByPickID(points[1]) as pickedVertexData,
      downPoint: picker.generatePickObjByPickID(points[2]) as pickedVertexData,
      xc: xc.map((i) => toString(i)).join(' '),
    });
  }, []);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-resample-curve', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const isFormDataValid = () => {
    const { curve, plane, limitPoint, upPoint, downPoint, xc } = formData;

    if (xc && xc.split(' ').length < 43) {
      MessageTip.error('比例值需要超过43个');
    }

    return (
      curve != null &&
      plane != null &&
      limitPoint != null &&
      upPoint != null &&
      downPoint != null &&
      xc.split(' ').length >= 43
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      plane: {
        type: 'number',
        format: PickInputRJSFFormat.PickPlane,
      },
      limitPoint: {
        type: 'number',
        format: PickInputRJSFFormat.PickVertex,
      },
      upPoint: {
        type: 'number',
        format: PickInputRJSFFormat.PickVertex,
      },
      downPoint: {
        type: 'number',
        format: PickInputRJSFFormat.PickVertex,
      },
      xc: {
        type: 'string',
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onPreview={preview}
      submitLoading={isLoading}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:autofocus': true,
        },
        plane: {
          'ui:placeholder': '请输入曲面',
        },
        limitPoint: {
          'ui:placeholder': '请输入翼型曲线左右极值点',
        },
        upPoint: {
          'ui:placeholder': '请输入翼型曲线上端点',
        },
        downPoint: {
          'ui:placeholder': '请输入翼型曲线下端点',
        },
        xc: {
          'ui:placeholder': '请输入比例值(0,1之间, 最少需要43个)',
        },
      }}
      submitText='完成'
      isFormDataValid={isFormDataValid()}
      onSubmit={checkAndFinishDraw}
    />
  );
}

export const cmdReSamplingCurve: CurvedBaseCommand = {
  id: 'CmdReSamplingCurve',
  label: 'command.resampling-curve',
  icon: 'commands/curved/resampling-curve',
  create: (label, onClose, props) => (
    <CommandReSamplingCurve
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
